package com.wst.wst_server.service.impl;

import com.wst.wst_server.controller.ResponseResult;
import com.wst.wst_server.entity.LoginUser;
import com.wst.wst_server.service.LoginService;
import com.wst.wst_server.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    AuthenticationManager authenticationManager;
    @Override
    public ResponseResult login(String username,String password) {
        //使用authenticationManager进行验证，authentication是用户填写的用户名和密码封装进这里
        Authentication authentication = new UsernamePasswordAuthenticationToken(username, password);

        //auth是认证之后的对象
        Authentication auth = authenticationManager.authenticate(authentication);
        if(auth==null)
            throw new RuntimeException("登录失败");

        //使用userid 生成jwt ，返回ResponseResult
        LoginUser loginUser = (LoginUser) auth.getPrincipal();
        Integer userid = loginUser.getUser().getId();
        String jwt = JwtUtil.createJWT(userid.toString());

        return new ResponseResult(200,"ok",jwt);
    }
}
